<template>
  <div class="form-container">
    <!-- 添加标题 -->
    <div class="header">编辑食堂店铺</div>
    <!-- 添加带下划线的文字 -->
    <p class="form-description">所有内容都不允许为空，最多可以上传1张图片</p>

    <el-form
        ref="form"
        :model="form"
        class="responsive-form"
        label-position="left"
        label-width="120px"
    >
      <el-form-item label="店铺名字" prop="shopName">
        <el-input v-model="form.shopName" placeholder="请输入店铺名字哦"></el-input>
      </el-form-item>
      <el-form-item label="所在食堂" prop="shopAt">
        <el-select v-model="form.shopAt" placeholder="请选择所在食堂">
          <el-option label="一食堂" value="一食堂"></el-option>
          <el-option label="二食堂" value="二食堂"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所在楼层" prop="shopFloor">
        <el-select v-model="form.shopFloor" placeholder="请选择所在楼层">
          <el-option label="一楼" value="一楼"></el-option>
          <el-option label="二楼" value="二楼"></el-option>
          <el-option label="三楼" value="三楼"></el-option>
          <el-option label="四楼" value="四楼"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="店铺描述" prop="shopDescription">
        <el-input v-model="form.shopDescription" placeholder="请输入店铺描述哦" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="支付方式" prop="shopPayment">
        <el-checkbox-group v-model="form.shopPayment">
          <el-checkbox value="校园卡">校园卡</el-checkbox>
          <el-checkbox value="微信支付">微信支付</el-checkbox>
          <el-checkbox value="云闪付">云闪付</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="店铺图片" prop="shopImage">
        <el-upload
            :action=uploadUrl
            :before-upload="beforeUpload"
            :file-list="fileList"
            :limit="1"
            :on-error="handleError"
            :on-exceed="handleExceed"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            accept="image/*"
            list-type="picture-card"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="位置指引" prop="shopRelativePosition">
        <el-input v-model="form.shopRelativePosition" placeholder="请输入位置指引（怎么找到你说的这家店呢？）"></el-input>
      </el-form-item>
      <!-- 提交按钮 -->
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
      </el-form-item>
    </el-form>

    <el-dialog v-model="dialogVisible" :visible.sync="dialogVisible" title="预览图片">
      <img :src="dialogImageUrl" alt="预览图片" style="width: 50%">
    </el-dialog>
  </div>
</template>

<script>
import {ElMessage} from "element-plus";
import axios from "axios";
import {inject} from "vue";

export default {
  setup() {
    const uploadUrl = inject("uploadUrl");
    return {uploadUrl};
  },
  data() {
    return {
      form: {
        shopName: '',
        shopAt: '',
        shopFloor: '',
        shopDescription: '',
        shopPayment: [],
        shopImage: '',
        shopRelativePosition: '',
      },
      fileList: [],
      isUploadDisabled: false,
      dialogImageUrl: '', // 预览图片的 URL
      dialogVisible: false, // 控制预览对话框的显示
    };
  },
  mounted() {
    this.getOriginalData();
  },
  methods: {
    // 获取原始数据 用于修改的时候数据回显
    getOriginalData() {
      axios.get('/canteenshop/get/single/' + this.$route.query.shopId).then(res => {
        console.log(res.data.data);
        this.form.shopName = res.data.data.shopName;
        this.form.shopAt = res.data.data.shopAt;
        this.form.shopFloor = res.data.data.shopFloor;
        this.form.shopDescription = res.data.data.shopDescription;
        this.form.shopPayment = res.data.data.shopPayment.split(',');
        this.form.shopImage = res.data.data.shopImage;
        this.form.shopRelativePosition = res.data.data.shopRelativePosition;
        if (this.form.shopImage) {
          this.fileList = [{
            name: '店铺图片',
            url: this.form.shopImage,
          }];
        }
      })
    },

    // 图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 移除图片
    handleRemove(file, fileList) {
      this.form.shopImage = ''; // 清空图片路径
      console.log(file, fileList);
    },
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt8M = file.size / 1024 / 1024 < 8; // 文件大小限制为 8MB
      if (!isImage) {
        this.$message.error('只能上传图片格式的文件!');
        return false; // 阻止上传
      }
      if (!isLt8M) {
        this.$message.error('上传的图片大小不能超过 8MB!');
        return false; // 阻止上传
      }
      return true; // 允许上传
    },
    // 上传成功回调
    handleSuccess(response, file, fileList) {
      this.$message.success('上传成功');
      // 假设上传成功后，后端返回图片的 URL
      this.form.shopImage = response.data; // 设置图片 URL 到 form 中
      console.log(this.form.shopImage);
      this.fileList = fileList; // 更新 fileList 状态
      console.log('上传成功', response);
    },
    // 上传失败回调
    handleError(err, file, fileList) {
      this.$message.error('上传失败');
      console.log(this.uploadUrl);
      console.error('上传失败', err);
    },
    // 超出上传限制时的回调
    handleExceed(files, fileList) {
      this.$message.warning('最多只能上传 1 张图片');
    },
    onSubmit() {
      // 构造请求数据
      const requestData = {
        shopName: this.form.shopName,
        shopAt: this.form.shopAt,
        shopFloor: this.form.shopFloor,
        shopDescription: this.form.shopDescription,
        shopPayment: this.form.shopPayment.join(','), // 将数组转换为字符串
        shopImage: this.form.shopImage,
        shopRelativePosition: this.form.shopRelativePosition,
      };
      // 校验表单数据是否完整
      if (
          this.form.shopName === '' || this.form.shopAt === '' ||
          this.form.shopFloor === '' || this.form.shopDescription === '' ||
          this.form.shopPayment.length === 0 || this.form.shopImage === '' ||
          this.form.shopRelativePosition === ''
      ) {
        ElMessage.error('所有内容都不许为空哦');
        return;
      }
      // 使用 axios 发起 PUT 请求
      axios.put('/canteenshop/update/' + this.$route.query.shopId, requestData)
          .then(response => {
            console.log(response.data.data);
            console.log(requestData.data);
            if (response.data.data === -1) {
              ElMessage.error('所有内容都不许为空');
            }
            ElMessage.success('更新成功');
            this.$router.push('/canteenShopDetail?shopId=' + this.$route.query.shopId); // 跳转到指定页面
          })
          .catch(error => {
            console.error(error);
            ElMessage.error('更新失败');
          });
    },
  }
}
</script>

<style scoped>
.form-container {
  margin: 20px 0; /* 调整外边距，使其向左对齐 */
  padding: 20px;
}

/* 添加标题样式 */
.header {
  background: none;
  padding-top: 5px;
  text-align: left;
  font-size: 20px;
  line-height: 30px;
  font-weight: bold;
}

/* 添加带下划线的文字样式 */
.form-description {
  border-bottom: 1px solid #ddd;
  padding-bottom: 5px;
  color: #666;
  text-align: left;
  line-height: 25px; /* 设置行高 */
}

.responsive-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 强制设置 placeholder 字体为 Zpix */
.form-container ::placeholder {
  font-family: "Zpix", sans-serif !important;
}

/* 强制设置输入框内容的字体为 Zpix */
.form-container input {
  font-family: "Zpix", sans-serif !important;
}
</style>